import { currentProject } from './../../../currentConfig';
import { adapter, currentFramework } from './adapter';
import { InitializationService } from './index';
import { PrividerService } from "./prividerService";
import { EventEmitter } from "@angular/core";
import * as R from "ramda";
const Component = require('@angular/core').Component;

@Component(adapter.warpComponentMeta({
    styleUrls: ['./index.scss'],
    template: `
        <div  class="connectLDc-contaiiner">
            <header>
                <i class="material-icons back divvma" (click)="onBack()">arrow_back</i>
                <h1 class="padding">连接本地数据中心</h1>
                <div class="nav">
                    <i ></i>
                    <i class="active">2</i>
                    <i ></i>
                    <i ></i>
                </div>
            </header>
            <div class="margin">
                <dl class="instruction">
                    <dt>使用{{currentProject=="chef"?'制作台':'传菜台'}}，需在收银台开启数据中心</dt>
                    <dd>1.在收银台中进入 "设置 -> 本地数据中心"</dd>
                    <dd>2.点击 "设置本终端为 '本地数据中心' 主机" 按钮设置收银台为本地数据中心</dd>
                    <dd>3.点击 "配置服务"， 勾选 "门店业务服务" 并确定</dd>
                </dl>
            </div>
           
            <div class="status margin" >
                <div class="input" *ngIf='checkStatus=="input"'>
                    <div class="title">手动设定本地数据中心</div>
                    <md-input-container floatingPlaceholder="false">
                        <input md-input placeholder="输入ip地址" [(ngModel)]="LDCIp" maxLength="100" />
                    </md-input-container>
                    <div class="btn-container">
                        <button class="btn-certain" (click)="findLDC()" >确定连接</button>
                        <button class="cancel" (click)="autoSearch()" >自动查找</button>
                    </div>
                </div>
                <div class="checking" *ngIf='checkStatus=="checking"'>
                     <div class="title" style="margin-bottom:30px;">正在连接本地数据中心</div>
                     <md-progress-bar mode="indeterminate" color="warning"></md-progress-bar>
                </div>
                <div class="failed" *ngIf='checkStatus=="failed"'>
                    <div class="title">手动设定本地数据中心</div>
                    <md-input-container floatingPlaceholder="false">
                        <input md-input placeholder="手动设定本地数据中心" [(ngModel)]="LDCIp" maxLength="100" />
                    </md-input-container>
                    <div class="warn">不能连接到本地数据中心</div>
                    <button class="cancel" (click)="reCheck()" >重新连接</button>
                </div>
            </div>
        </div>
    `
}))
export default class ConnectLDC {
    constructor(
    ) {
        setTimeout(() => {
            if (!PrividerService.current.doLocalstorageGetItem("preLDCs")) {
                this.autoSearch();
            }
        }, 0);
    }
    private LDCIp = "";
    private checkStatus: string = "input";
    private system;
    private event = new EventEmitter<any>();
    private currentProject = currentProject;
    stop() {
        this.event.emit();
    }
    reCheck() {
        this.findLDC()
    }
    onBack() {
        this.stop();
        PrividerService.current.navigate(InitializationService.current.getPathByComponentName("welcome"))
    }
    getLDCsFoundedResult(): Promise<any[]> {
        return new Promise(async (resove, reject) => {
            this.event.subscribe(() => {
                reject();
            })
            const ipAhead = this.getHeadIp();
            var found = (await Promise.all(R.range(0, 255).map(async (i) => {
                try {
                    const ip = ipAhead + "." + i;
                    const storeId = (<any>(await PrividerService.current.fetchStoreIdByIDCIp(ip, {
                        timeout: 15000
                    }))).storeId;
                    return { storeId, ip }
                } catch (e) {
                    return
                }
            }))).filter(x => x);
            if (found.length > 0) {
                resove(found);
            } else {
                reject();
            }
        })
    }

    async autoSearch() {
        try {
            this.checkStatus = "checking";
            const found = await this.getLDCsFoundedResult();
            PrividerService.current.doLocalstorageSetItem("preLDCs", found)
            this.findLDCSuccess();
        } catch (error) {
            this.checkStatus = "failed";
        }
    }

    getHeadIp() {
        let ip = ((<any>window).device && (<any>window).device.getDeviceInfo().ip) || "172.16.255.83";
        let index = ip.lastIndexOf(".");
        let ipAhead = ip.substring(0, index);
        return ipAhead;
    }


    findLDCSuccess() {
        setTimeout(() => {
            this.checkStatus = "passed";
            PrividerService.current.navigate(InitializationService.current.getPathByComponentName("checkEnv"))
        }, 1000);
    }

    async findLDC() {
        try {
            this.checkStatus = "checking";
            const storeId = (<any>(await PrividerService.current.fetchStoreIdByIDCIp(this.LDCIp))).storeId;
            const ip = this.LDCIp;
            PrividerService.current.doLocalstorageSetItem("preLDCs", [{ storeId, ip }])
            this.findLDCSuccess();
        } catch (error) {
            console.log(error)
            this.checkStatus = "failed";
        }

    }
}



